using System;
using Gtk;
using System.IO;
using DaphneTranslator.BusinessLogic;

namespace DaphneTranslator
{
	[System.ComponentModel.ToolboxItem(true)]
	public partial class PathWidget : Gtk.Bin
	{
		public PathWidget ()
		{
			this.Build ();
			
			btnSelectFolder.Clicked += SelectFolder;
			this.SelectRelativePath = false;
		}
		
		public string RootPath
		{ get; set; }
		
		public bool SelectRelativePath
		{ get; set; }

		private void SelectFolder (object sender, EventArgs e)
		{
			FileChooserDialog dlg = new FileChooserDialog (
						"Choose directory for save",
			null, FileChooserAction.SelectFolder,
			"Cancel", ResponseType.Cancel, "Select", ResponseType.Accept, null);
			dlg.SelectMultiple = false;
			dlg.DestroyWithParent = true;
			string sSetPath = GetPath ();
			if (SelectRelativePath == true) {
				sSetPath = System.IO.Path.Combine (RootPath, sSetPath);
			}
			dlg.SetFilename(sSetPath);
			dlg.Modal = true;
			ResponseType res = (ResponseType)dlg.Run ();
			string sPath = dlg.Filename;
			dlg.Destroy ();
			if (res == ResponseType.Accept) {
				if (SelectRelativePath == true) {
					try {
						string sRelativePath = DirectoryHelper.RelativePath (dlg.Filename, RootPath);
						SetPath (sRelativePath.Trim ());
						
					} catch {
						MessageDialog msg = new MessageDialog (null, DialogFlags.Modal, MessageType.Error,
				                                      ButtonsType.Ok, "Selected path is not relative to the root folder.");
						msg.Run ();		
						msg.Destroy ();					
					}					
				}
				else
				{					
					SetPath (sPath.Trim ());
				}
			}						
		}
		
		public void SetPath (string sPath)
		{
			lblPath.Text = sPath.Trim ();			
		}
		
		public string GetPath ()
		{
			return lblPath.Text;
		}
	}

}

